package com.whfc.cncit.helmet.processor;

import com.whfc.cncit.constant.CncitConst;
import com.whfc.cncit.entity.CncitDwMsgPS;
import com.whfc.cncit.entity.CncitUpMsgS;
import com.whfc.cncit.helmet.util.CncitMsgUtil;
import com.whfc.common.constant.QueueConst;
import com.whfc.common.util.JSONUtil;
import com.whfc.emp.enums.HelmetType;
import com.whfc.iot.session.Session;
import com.whfc.iot.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/10/26 11:37
 */
@Component
public class HelmetUpMsgProcessorS implements CncitUpMsgProcessor<CncitUpMsgS> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private SessionManager sessionManager;

    private static final int ALARM_YES = 1;

    private static final String WARN_TTS_CONTENT = "请正确使用安全帽";

    @Override
    public void processMsg(CncitUpMsgS msg) {

        //解析报警值
        int alarmValue = msg.getAlarmValue();
        int aBit1 = CncitMsgUtil.getBitValue(alarmValue, 1);
        int aBit2 = CncitMsgUtil.getBitValue(alarmValue, 2);
        int aBit3 = CncitMsgUtil.getBitValue(alarmValue, 3);
        int aBit6 = CncitMsgUtil.getBitValue(alarmValue, 6);
        int aBit7 = CncitMsgUtil.getBitValue(alarmValue, 7);
        int alarmDrop = aBit1;
        int alarmCrash = aBit2;
        int alarmSos = aBit3;
        int alarmStill = aBit6;
        int alarmDoff = aBit7;

        msg.setAlarmDrop(alarmDrop);
        msg.setAlarmSos(alarmSos);
        msg.setAlarmCrash(alarmCrash);
        msg.setAlarmStill(alarmStill);
        msg.setAlarmDoff(alarmDoff);

        try {
            String textMsg = JSONUtil.toString(msg);
            logger.info("处理安全帽数据:{}", textMsg);
            amqpTemplate.convertAndSend(QueueConst.EMP_HELMET_DATA, textMsg);
        } catch (Exception ex) {
            logger.error("", ex);
        }

        // 语音提醒
        if (!String.valueOf(HelmetType.VOICE.getValue()).equals(msg.getExt1())) {
            return;
        }

        try {
            if (ALARM_YES == alarmDrop || ALARM_YES == alarmCrash || ALARM_YES == alarmSos || ALARM_YES == alarmStill || ALARM_YES == alarmDoff) {
                // 发送语音提醒
                Session session = sessionManager.getSessionByDeviceId(msg.getDeviceId());
                CncitDwMsgPS cncitDwMsgPS = new CncitDwMsgPS();
                cncitDwMsgPS.setType(CncitConst.CMD_TTSD);
                cncitDwMsgPS.setParam(WARN_TTS_CONTENT);
                cncitDwMsgPS.setDeviceCode(msg.getDeviceCode());
                session.getChannel().writeAndFlush(cncitDwMsgPS);
            }
        } catch (Exception e) {
            logger.error("发送语音播报失败", e);
        }

    }
}
